/*      */ package com.zimbra.qa.unittest;
/*      */ 
/*      */ import com.google.common.collect.Lists;
/*      */ import com.google.common.io.Closeables;
/*      */ import com.zimbra.client.ZContact;
/*      */ import com.zimbra.client.ZDataSource;
/*      */ import com.zimbra.client.ZDateTime;
/*      */ import com.zimbra.client.ZDocument;
/*      */ import com.zimbra.client.ZEmailAddress;
/*      */ import com.zimbra.client.ZFilterRule;
/*      */ import com.zimbra.client.ZFilterRules;
/*      */ import com.zimbra.client.ZFolder;
/*      */ import com.zimbra.client.ZFolder.View;
/*      */ import com.zimbra.client.ZGetInfoResult;
/*      */ import com.zimbra.client.ZGetMessageParams;
/*      */ import com.zimbra.client.ZGrant.GranteeType;
/*      */ import com.zimbra.client.ZIdentity;
/*      */ import com.zimbra.client.ZInvite;
/*      */ import com.zimbra.client.ZInvite.ZAttendee;
/*      */ import com.zimbra.client.ZInvite.ZClass;
/*      */ import com.zimbra.client.ZInvite.ZComponent;
/*      */ import com.zimbra.client.ZInvite.ZOrganizer;
/*      */ import com.zimbra.client.ZInvite.ZParticipantStatus;
/*      */ import com.zimbra.client.ZInvite.ZRole;
/*      */ import com.zimbra.client.ZInvite.ZStatus;
/*      */ import com.zimbra.client.ZInvite.ZTransparency;
/*      */ import com.zimbra.client.ZItem.Flag;
/*      */ import com.zimbra.client.ZMailbox;
/*      */ import com.zimbra.client.ZMailbox.ContactSortBy;
/*      */ import com.zimbra.client.ZMailbox.Options;
/*      */ import com.zimbra.client.ZMailbox.OwnerBy;
/*      */ import com.zimbra.client.ZMailbox.ReplyVerb;
/*      */ import com.zimbra.client.ZMailbox.SharedItemBy;
/*      */ import com.zimbra.client.ZMailbox.ZAppointmentResult;
/*      */ import com.zimbra.client.ZMailbox.ZImportStatus;
/*      */ import com.zimbra.client.ZMailbox.ZOutgoingMessage;
/*      */ import com.zimbra.client.ZMailbox.ZOutgoingMessage.AttachedMessagePart;
/*      */ import com.zimbra.client.ZMailbox.ZOutgoingMessage.MessagePart;
/*      */ import com.zimbra.client.ZMessage;
/*      */ import com.zimbra.client.ZMessage.ZMimePart;
/*      */ import com.zimbra.client.ZMountpoint;
/*      */ import com.zimbra.client.ZPrefs;
/*      */ import com.zimbra.client.ZSearchHit;
/*      */ import com.zimbra.client.ZSearchParams;
/*      */ import com.zimbra.client.ZSearchResult;
/*      */ import com.zimbra.client.ZTag;
/*      */ import com.zimbra.common.account.Key.AccountBy;
/*      */ import com.zimbra.common.account.Key.DataSourceBy;
/*      */ import com.zimbra.common.account.Key.DistributionListBy;
/*      */ import com.zimbra.common.auth.ZAuthToken;
/*      */ import com.zimbra.common.lmtp.LmtpClient;
/*      */ import com.zimbra.common.localconfig.ConfigException;
/*      */ import com.zimbra.common.localconfig.KnownKey;
/*      */ import com.zimbra.common.localconfig.LC;
/*      */ import com.zimbra.common.localconfig.LocalConfig;
/*      */ import com.zimbra.common.service.ServiceException;
/*      */ import com.zimbra.common.soap.AdminConstants;
/*      */ import com.zimbra.common.soap.Element;
/*      */ import com.zimbra.common.soap.Element.Attribute;
/*      */ import com.zimbra.common.soap.Element.XMLElement;
/*      */ import com.zimbra.common.soap.SoapFaultException;
/*      */ import com.zimbra.common.soap.SoapHttpTransport;
/*      */ import com.zimbra.common.soap.SoapTransport;
/*      */ import com.zimbra.common.util.ByteUtil;
/*      */ import com.zimbra.common.util.CliUtil;
/*      */ import com.zimbra.common.util.Log;
/*      */ import com.zimbra.common.util.StringUtil;
/*      */ import com.zimbra.common.util.ZimbraLog;
/*      */ import com.zimbra.common.zmime.ZMimeMessage;
/*      */ import com.zimbra.cs.account.Account;
/*      */ import com.zimbra.cs.account.Config;
/*      */ import com.zimbra.cs.account.DataSource;
/*      */ import com.zimbra.cs.account.DistributionList;
/*      */ import com.zimbra.cs.account.Domain;
/*      */ import com.zimbra.cs.account.Provisioning;
/*      */ import com.zimbra.cs.account.Server;
/*      */ import com.zimbra.cs.account.soap.SoapProvisioning;
/*      */ import com.zimbra.cs.client.LmcSession;
/*      */ import com.zimbra.cs.client.soap.LmcAdminAuthRequest;
/*      */ import com.zimbra.cs.client.soap.LmcAdminAuthResponse;
/*      */ import com.zimbra.cs.client.soap.LmcAuthRequest;
/*      */ import com.zimbra.cs.client.soap.LmcAuthResponse;
/*      */ import com.zimbra.cs.client.soap.LmcSoapClientException;
/*      */ import com.zimbra.cs.db.DbMailItem;
/*      */ import com.zimbra.cs.db.DbPool;
/*      */ import com.zimbra.cs.db.DbPool.DbConnection;
/*      */ import com.zimbra.cs.db.DbUtil;
/*      */ import com.zimbra.cs.index.SortBy;
/*      */ import com.zimbra.cs.index.ZimbraHit;
/*      */ import com.zimbra.cs.index.ZimbraQueryResults;
/*      */ import com.zimbra.cs.mailbox.DeliveryOptions;
/*      */ import com.zimbra.cs.mailbox.Flag;
/*      */ import com.zimbra.cs.mailbox.Folder;
/*      */ import com.zimbra.cs.mailbox.MailItem.Type;
/*      */ import com.zimbra.cs.mailbox.MailServiceException;
/*      */ import com.zimbra.cs.mailbox.Mailbox;
/*      */ import com.zimbra.cs.mailbox.MailboxIndex;
/*      */ import com.zimbra.cs.mailbox.Message;
/*      */ import com.zimbra.cs.mailbox.OperationContext;
/*      */ import com.zimbra.cs.mime.ParsedMessage;
/*      */ import com.zimbra.cs.store.StoreManager;
/*      */ import com.zimbra.cs.store.file.FileBlobStore;
/*      */ import com.zimbra.cs.util.BuildInfo;
/*      */ import com.zimbra.cs.util.JMSession;
/*      */ import com.zimbra.qa.unittest.prov.soap.SoapTest;
/*      */ import com.zimbra.soap.account.message.AuthRequest;
/*      */ import com.zimbra.soap.account.message.AuthResponse;
/*      */ import com.zimbra.soap.admin.message.GetAccountRequest;
/*      */ import com.zimbra.soap.admin.message.GetAccountResponse;
/*      */ import com.zimbra.soap.admin.message.GrantRightRequest;
/*      */ import com.zimbra.soap.admin.message.GrantRightResponse;
/*      */ import com.zimbra.soap.admin.message.ReloadLocalConfigRequest;
/*      */ import com.zimbra.soap.admin.message.ReloadLocalConfigResponse;
/*      */ import com.zimbra.soap.admin.type.AccountInfo;
/*      */ import com.zimbra.soap.admin.type.Attr;
/*      */ import com.zimbra.soap.admin.type.DataSourceType;
/*      */ import com.zimbra.soap.admin.type.EffectiveRightsTargetSelector;
/*      */ import com.zimbra.soap.admin.type.GranteeSelector;
/*      */ import com.zimbra.soap.admin.type.GranteeSelector.GranteeBy;
/*      */ import com.zimbra.soap.admin.type.RightModifierInfo;
/*      */ import com.zimbra.soap.type.AccountBy;
/*      */ import com.zimbra.soap.type.AccountSelector;
/*      */ import com.zimbra.soap.type.GranteeType;
/*      */ import com.zimbra.soap.type.TargetBy;
/*      */ import com.zimbra.soap.type.TargetType;
/*      */ import java.io.BufferedReader;
/*      */ import java.io.ByteArrayInputStream;
/*      */ import java.io.ByteArrayOutputStream;
/*      */ import java.io.IOException;
/*      */ import java.io.InputStream;
/*      */ import java.io.StringReader;
/*      */ import java.util.ArrayList;
/*      */ import java.util.Arrays;
/*      */ import java.util.Collections;
/*      */ import java.util.Date;
/*      */ import java.util.HashMap;
/*      */ import java.util.List;
/*      */ import java.util.Map;
/*      */ import java.util.Set;
/*      */ import java.util.TreeSet;
/*      */ import javax.mail.MessagingException;
/*      */ import javax.mail.internet.MimeMessage;
/*      */ import javax.mail.util.SharedByteArrayInputStream;
/*      */ import junit.framework.Assert;
/*      */ import org.dom4j.DocumentException;
/*      */ import org.junit.runner.JUnitCore;
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ public class TestUtil
/*      */   extends Assert
/*      */ {
/*      */   public static final String DEFAULT_PASSWORD = "test123";
/*  167 */   public static boolean fromRunUnitTests = false;
/*      */   
/*      */   public static boolean accountExists(String userName) throws ServiceException {
/*  170 */     return AccountTestUtil.accountExists(userName);
/*      */   }
/*      */   
/*      */   public static Account getAccount(String userName) throws ServiceException {
/*  174 */     return AccountTestUtil.getAccount(userName);
/*      */   }
/*      */   
/*      */   public static String getDomain() throws ServiceException {
/*  178 */     return AccountTestUtil.getDomain();
/*      */   }
/*      */   
/*      */   public static Mailbox getMailbox(String userName) throws ServiceException {
/*  182 */     return AccountTestUtil.getMailbox(userName);
/*      */   }
/*      */   
/*      */   public static String getAddress(String userName) throws ServiceException {
/*  186 */     return AccountTestUtil.getAddress(userName);
/*      */   }
/*      */   
/*      */   public static String getAddress(String userName, String domainName) {
/*  190 */     return AccountTestUtil.getAddress(userName, domainName);
/*      */   }
/*      */   
/*      */   public static String getSoapUrl() {
/*      */     try {
/*  195 */       return getBaseUrl() + "/service/soap/";
/*      */     } catch (ServiceException e) {
/*  197 */       ZimbraLog.test.error("Unable to determine SOAP URL", e);
/*      */     }
/*  199 */     return null;
/*      */   }
/*      */   
/*      */   public static String getBaseUrl()
/*      */     throws ServiceException
/*      */   {
/*  205 */     int port = Provisioning.getInstance().getLocalServer().getIntAttr("zimbraMailPort", 0);
/*  206 */     String scheme; String scheme; if (port > 0) {
/*  207 */       scheme = "http";
/*      */     } else {
/*  209 */       port = Provisioning.getInstance().getLocalServer().getIntAttr("zimbraMailSSLPort", 0);
/*  210 */       scheme = "https";
/*      */     }
/*  212 */     return scheme + "://localhost:" + port;
/*      */   }
/*      */   
/*      */   public static String getAdminSoapUrl() {
/*      */     int port;
/*      */     try {
/*  218 */       port = Provisioning.getInstance().getLocalServer().getIntAttr("zimbraAdminPort", 0);
/*      */     } catch (ServiceException e) {
/*  220 */       ZimbraLog.test.error("Unable to get admin SOAP port", e);
/*  221 */       port = LC.zimbra_admin_service_port.intValue();
/*      */     }
/*  223 */     return "https://localhost:" + port + "/service/admin/soap/";
/*      */   }
/*      */   
/*      */   public static LmcSession getSoapSession(String userName) throws ServiceException, LmcSoapClientException, IOException, SoapFaultException
/*      */   {
/*  228 */     LmcAuthRequest auth = new LmcAuthRequest();
/*  229 */     auth.setUsername(getAddress(userName));
/*  230 */     auth.setPassword("test123");
/*  231 */     LmcAuthResponse authResp = (LmcAuthResponse)auth.invoke(getSoapUrl());
/*  232 */     return authResp.getSession();
/*      */   }
/*      */   
/*      */   public static LmcSession getAdminSoapSession() throws Exception
/*      */   {
/*  237 */     LmcAdminAuthRequest auth = new LmcAdminAuthRequest();
/*  238 */     auth.setUsername(LC.zimbra_ldap_user.value());
/*  239 */     auth.setPassword(LC.zimbra_ldap_password.value());
/*  240 */     LmcAdminAuthResponse authResp = (LmcAdminAuthResponse)auth.invoke(getAdminSoapUrl());
/*  241 */     return authResp.getSession();
/*      */   }
/*      */   
/*      */   public static Message addMessage(Mailbox mbox, String subject) throws Exception {
/*  245 */     return addMessage(mbox, 2, subject, System.currentTimeMillis());
/*      */   }
/*      */   
/*      */   public static Message addMessage(Mailbox mbox, int folderId, String subject, long timestamp) throws Exception {
/*  249 */     String message = getTestMessage(subject, null, null, new Date(timestamp));
/*  250 */     ParsedMessage pm = new ParsedMessage(message.getBytes(), Long.valueOf(timestamp), false);
/*  251 */     DeliveryOptions dopt = new DeliveryOptions().setFolderId(folderId).setFlags(Flag.BITMASK_UNREAD);
/*  252 */     return mbox.addMessage(null, pm, dopt, null);
/*      */   }
/*      */   
/*      */   public static Message addMessage(Mailbox mbox, ParsedMessage pm) throws Exception {
/*  256 */     DeliveryOptions dopt = new DeliveryOptions().setFolderId(2).setFlags(Flag.BITMASK_UNREAD);
/*  257 */     return mbox.addMessage(null, pm, dopt, null);
/*      */   }
/*      */   
/*      */   public static Message addMessage(Mailbox mbox, String recipient, String sender, String subject, String body, long timestamp) throws Exception
/*      */   {
/*  262 */     String message = getTestMessage(subject, recipient, sender, body, new Date(timestamp));
/*  263 */     ParsedMessage pm = new ParsedMessage(message.getBytes(), Long.valueOf(timestamp), false);
/*  264 */     return addMessage(mbox, pm);
/*      */   }
/*      */   
/*      */   public static String getTestMessage(String subject) throws ServiceException, MessagingException, IOException {
/*  268 */     return new MessageBuilder().withSubject(subject).create();
/*      */   }
/*      */   
/*      */   public static String getTestMessage(String subject, String recipient, String sender, Date date) throws ServiceException, MessagingException, IOException
/*      */   {
/*  273 */     return new MessageBuilder().withSubject(subject).withToRecipient(recipient).withFrom(sender).withDate(date).create();
/*      */   }
/*      */   
/*      */   public static String getTestMessage(String subject, String recipient, String sender, String body, Date date)
/*      */     throws ServiceException, MessagingException, IOException
/*      */   {
/*  279 */     return new MessageBuilder().withSubject(subject).withToRecipient(recipient).withFrom(sender).withDate(date).withBody(body).create();
/*      */   }
/*      */   
/*      */   static String addDomainIfNecessary(String user) throws ServiceException
/*      */   {
/*  284 */     if ((StringUtil.isNullOrEmpty(user)) || (user.contains("@"))) {
/*  285 */       return user;
/*      */     }
/*  287 */     return String.format("%s@%s", new Object[] { user, getDomain() });
/*      */   }
/*      */   
/*      */   public static boolean addMessageLmtp(String subject, String recipient, String sender) throws Exception {
/*  291 */     return addMessageLmtp(subject, new String[] { recipient }, sender);
/*      */   }
/*      */   
/*      */   public static boolean addMessageLmtp(String subject, String[] recipients, String sender) throws Exception {
/*  295 */     String message = getTestMessage(subject, recipients[0], sender, null);
/*  296 */     return addMessageLmtp(recipients, sender, message);
/*      */   }
/*      */   
/*      */   public static boolean addMessageLmtp(String subject, String[] recipients, String sender, String body) throws Exception
/*      */   {
/*  301 */     String message = getTestMessage(subject, recipients[0], sender, body, null);
/*  302 */     return addMessageLmtp(recipients, sender, message);
/*      */   }
/*      */   
/*      */   public static boolean addMessageLmtp(String[] recipients, String sender, String message) throws Exception {
/*  306 */     String[] recipWithDomain = new String[recipients.length];
/*  307 */     for (int i = 0; i < recipients.length; i++) {
/*  308 */       recipWithDomain[i] = addDomainIfNecessary(recipients[i]);
/*      */     }
/*  310 */     Provisioning prov = Provisioning.getInstance();
/*  311 */     LmtpClient lmtp = new LmtpClient("localhost", prov.getLocalServer().getIntAttr("zimbraLmtpBindPort", 7025));
/*      */     
/*  313 */     byte[] data = message.getBytes();
/*  314 */     String senderAddress = "";
/*  315 */     if (!StringUtil.isNullOrEmpty(sender)) {
/*  316 */       senderAddress = addDomainIfNecessary(sender);
/*      */     }
/*  318 */     boolean success = lmtp.sendMessage(new ByteArrayInputStream(data), recipWithDomain, senderAddress, "TestUtil", Long.valueOf(data.length));
/*      */     
/*  320 */     lmtp.close();
/*  321 */     return success;
/*      */   }
/*      */   
/*      */   public static String addMessage(ZMailbox mbox, String subject) throws ServiceException, IOException, MessagingException
/*      */   {
/*  326 */     return addMessage(mbox, subject, Integer.toString(2));
/*      */   }
/*      */   
/*      */   public static String addMessage(ZMailbox mbox, String subject, String folderId) throws ServiceException, IOException, MessagingException
/*      */   {
/*  331 */     String message = getTestMessage(subject);
/*  332 */     return mbox.addMessage(folderId, null, null, 0L, message, true);
/*      */   }
/*      */   
/*      */   public static String addMessage(ZMailbox mbox, String subject, String folderId, String flags) throws ServiceException, IOException, MessagingException
/*      */   {
/*  337 */     String message = getTestMessage(subject);
/*  338 */     return mbox.addMessage(folderId, flags, null, 0L, message, true);
/*      */   }
/*      */   
/*      */   public static String addRawMessage(ZMailbox mbox, String rawMessage) throws ServiceException {
/*  342 */     return mbox.addMessage(Integer.toString(2), null, null, 0L, rawMessage, true);
/*      */   }
/*      */   
/*      */   public static void sendMessage(ZMailbox senderMbox, String recipientName, String subject) throws Exception {
/*  346 */     String body = getTestMessage(subject);
/*  347 */     sendMessage(senderMbox, recipientName, subject, body);
/*      */   }
/*      */   
/*      */   public static void sendMessage(ZMailbox senderMbox, String recipientName, String subject, String body) throws Exception
/*      */   {
/*  352 */     sendMessage(senderMbox, recipientName, subject, body, null);
/*      */   }
/*      */   
/*      */   public static void sendMessage(ZMailbox senderMbox, String recipientName, String subject, String body, String attachmentUploadId) throws Exception
/*      */   {
/*  357 */     ZMailbox.ZOutgoingMessage msg = getOutgoingMessage(recipientName, subject, body, attachmentUploadId);
/*  358 */     senderMbox.sendMessage(msg, null, false);
/*      */   }
/*      */   
/*      */   public static void saveDraftAndSendMessage(ZMailbox senderMbox, String recipient, String subject, String body, String attachmentUploadId) throws ServiceException
/*      */   {
/*  363 */     ZMailbox.ZOutgoingMessage outgoingDraft = getOutgoingMessage(recipient, subject, body, attachmentUploadId);
/*  364 */     ZMessage draft = senderMbox.saveDraft(outgoingDraft, null, Integer.toString(6));
/*      */     
/*  366 */     ZMailbox.ZOutgoingMessage outgoing = getOutgoingMessage(recipient, subject, body, null);
/*  367 */     if (attachmentUploadId != null) {
/*  368 */       ZMailbox.ZOutgoingMessage.AttachedMessagePart part = new ZMailbox.ZOutgoingMessage.AttachedMessagePart(draft.getId(), "2", null);
/*  369 */       outgoing.setMessagePartsToAttach(Arrays.asList(new ZMailbox.ZOutgoingMessage.AttachedMessagePart[] { part }));
/*      */     }
/*  371 */     senderMbox.sendMessage(outgoing, null, false);
/*      */   }
/*      */   
/*      */   public static ZMailbox.ZOutgoingMessage getOutgoingMessage(String recipient, String subject, String body, String attachmentUploadId) throws ServiceException
/*      */   {
/*  376 */     ZMailbox.ZOutgoingMessage msg = new ZMailbox.ZOutgoingMessage();
/*  377 */     List<ZEmailAddress> addresses = new ArrayList();
/*  378 */     addresses.add(new ZEmailAddress(addDomainIfNecessary(recipient), null, null, "t"));
/*  379 */     msg.setAddresses(addresses);
/*  380 */     msg.setSubject(subject);
/*  381 */     msg.setMessagePart(new ZMailbox.ZOutgoingMessage.MessagePart("text/plain", body));
/*  382 */     msg.setAttachmentUploadId(attachmentUploadId);
/*  383 */     return msg;
/*      */   }
/*      */   
/*      */ 
/*      */   public static List<Integer> search(Mailbox mbox, String query, MailItem.Type type)
/*      */     throws ServiceException
/*      */   {
/*  390 */     return search(mbox, query, Collections.singleton(type));
/*      */   }
/*      */   
/*      */ 
/*      */   public static List<Integer> search(Mailbox mbox, String query, Set<MailItem.Type> types)
/*      */     throws ServiceException
/*      */   {
/*  397 */     List<Integer> ids = new ArrayList();
/*  398 */     ZimbraQueryResults r = mbox.index.search(new OperationContext(mbox), query, types, SortBy.DATE_DESC, 100);
/*  399 */     while (r.hasNext()) {
/*  400 */       ZimbraHit hit = r.getNext();
/*  401 */       ids.add(new Integer(hit.getItemId()));
/*      */     }
/*  403 */     Closeables.closeQuietly(r);
/*  404 */     return ids;
/*      */   }
/*      */   
/*      */   public static List<ZimbraHit> searchForHits(Mailbox mbox, String query, MailItem.Type type) throws Exception {
/*  408 */     return searchForHits(mbox, query, Collections.singleton(type));
/*      */   }
/*      */   
/*      */   public static List<ZimbraHit> searchForHits(Mailbox mbox, String query, Set<MailItem.Type> types) throws Exception {
/*  412 */     List<ZimbraHit> hits = Lists.newArrayList();
/*  413 */     ZimbraQueryResults r = mbox.index.search(new OperationContext(mbox), query, types, SortBy.DATE_DESC, 100);
/*  414 */     while (r.hasNext()) {
/*  415 */       hits.add(r.getNext());
/*      */     }
/*  417 */     Closeables.closeQuietly(r);
/*  418 */     return hits;
/*      */   }
/*      */   
/*      */   public static List<String> search(ZMailbox mbox, String query, String type) throws ServiceException {
/*  422 */     List<String> ids = new ArrayList();
/*  423 */     ZSearchParams params = new ZSearchParams(query);
/*  424 */     params.setTypes(type);
/*  425 */     for (ZSearchHit hit : mbox.search(params).getHits()) {
/*  426 */       ids.add(hit.getId());
/*      */     }
/*  428 */     return ids;
/*      */   }
/*      */   
/*      */   public static List<ZMessage> search(ZMailbox mbox, String query) throws ServiceException {
/*  432 */     ZSearchParams params = new ZSearchParams(query);
/*  433 */     params.setTypes("message");
/*      */     
/*  435 */     return search(mbox, params);
/*      */   }
/*      */   
/*      */   public static List<ZMessage> search(ZMailbox mbox, ZSearchParams params) throws ServiceException {
/*  439 */     List<ZMessage> msgs = new ArrayList();
/*  440 */     for (ZSearchHit hit : mbox.search(params).getHits()) {
/*  441 */       ZGetMessageParams msgParams = new ZGetMessageParams();
/*  442 */       msgParams.setId(hit.getId());
/*  443 */       msgs.add(mbox.getMessage(msgParams));
/*      */     }
/*  445 */     return msgs;
/*      */   }
/*      */   
/*      */   public static List<String> searchMessageIds(ZMailbox mbox, ZSearchParams params) throws ServiceException {
/*  449 */     List<String> msgsIds = new ArrayList();
/*  450 */     ZSearchResult results = mbox.search(params);
/*  451 */     for (ZSearchHit hit : results.getHits()) {
/*  452 */       msgsIds.add(hit.getId());
/*      */     }
/*  454 */     return msgsIds;
/*      */   }
/*      */   
/*      */ 
/*      */   public static String getContent(ZMailbox mbox, String msgId)
/*      */     throws ServiceException
/*      */   {
/*  461 */     ZGetMessageParams msgParams = new ZGetMessageParams();
/*  462 */     msgParams.setId(msgId);
/*  463 */     msgParams.setRawContent(true);
/*  464 */     ZMessage msg = mbox.getMessage(msgParams);
/*  465 */     return msg.getContent();
/*      */   }
/*      */   
/*      */   public static byte[] getContent(ZMailbox mbox, String msgId, String name) throws ServiceException, IOException {
/*  469 */     ZMessage msg = mbox.getMessageById(msgId);
/*  470 */     ZMessage.ZMimePart part = getPart(msg, name);
/*  471 */     if (part == null) {
/*  472 */       return null;
/*      */     }
/*  474 */     return ByteUtil.getContent(mbox.getRESTResource("?id=" + msgId + "&part=" + part.getPartName()), 1024);
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public static ZMessage.ZMimePart getPart(ZMessage msg, String name)
/*      */   {
/*  481 */     return getPart(msg.getMimeStructure(), name);
/*      */   }
/*      */   
/*      */   private static ZMessage.ZMimePart getPart(ZMessage.ZMimePart mimeStructure, String name) {
/*  485 */     for (ZMessage.ZMimePart child : mimeStructure.getChildren()) {
/*  486 */       ZMessage.ZMimePart part = getPart(child, name);
/*  487 */       if (part != null) {
/*  488 */         return part;
/*      */       }
/*      */     }
/*  491 */     if ((StringUtil.equalIgnoreCase(mimeStructure.getName(), name)) || (StringUtil.equalIgnoreCase(mimeStructure.getFileName(), name)) || (StringUtil.equalIgnoreCase(mimeStructure.getPartName(), name)))
/*      */     {
/*      */ 
/*  494 */       return mimeStructure;
/*      */     }
/*  496 */     return null;
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   public static List<ZMessage> waitForMessages(ZMailbox mbox, String query, int numMsgsExpected, int timeout_millis)
/*      */     throws ServiceException
/*      */   {
/*  507 */     int orig_timeout_millis = timeout_millis;
/*  508 */     List<ZMessage> msgs = Lists.newArrayListWithExpectedSize(0);
/*  509 */     while (timeout_millis > 0) {
/*  510 */       msgs = search(mbox, query);
/*  511 */       if ((numMsgsExpected > 0) && (msgs.size() == numMsgsExpected)) {
/*  512 */         return msgs;
/*      */       }
/*  514 */       if (msgs.size() > numMsgsExpected) {
/*  515 */         Assert.fail("Unexpected number of messages (" + msgs.size() + ") returned by query '" + query + "'");
/*      */       }
/*      */       try {
/*  518 */         if (timeout_millis > 100) {
/*  519 */           Thread.sleep(100L);
/*  520 */           timeout_millis -= 100;
/*      */         } else {
/*  522 */           Thread.sleep(timeout_millis);
/*  523 */           timeout_millis = 0;
/*      */         }
/*      */       }
/*      */       catch (InterruptedException e) {
/*  527 */         ZimbraLog.test.debug("sleep got interrupted", e);
/*      */       }
/*      */     }
/*  530 */     if (numMsgsExpected > 0) {
/*  531 */       Assert.fail(String.format("Message%s for query '%s' didn't arrive within %d millisecs.  %s", new Object[] { numMsgsExpected == 1 ? "" : "s", query, Integer.valueOf(orig_timeout_millis), "Either the MTA is not running or the test failed." }));
/*      */     }
/*      */     
/*      */ 
/*  535 */     return msgs;
/*      */   }
/*      */   
/*      */   public static ZMessage waitForMessage(ZMailbox mbox, String query) throws Exception {
/*  539 */     List<ZMessage> msgs = waitForMessages(mbox, query, 1, 10000);
/*  540 */     return (ZMessage)msgs.get(0);
/*      */   }
/*      */   
/*      */ 
/*      */   public static Folder getFolderByPath(Mailbox mbox, String path)
/*      */     throws Exception
/*      */   {
/*  547 */     Folder folder = null;
/*      */     try {
/*  549 */       folder = mbox.getFolderByPath(null, path);
/*      */     } catch (MailServiceException e) {
/*  551 */       if (e.getCode() != "mail.NO_SUCH_FOLDER") {
/*  552 */         throw e;
/*      */       }
/*      */     }
/*  555 */     return folder;
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */   public static void deleteTestData(String userName, String subjectSubstring)
/*      */     throws ServiceException
/*      */   {
/*  564 */     ZMailbox mbox = getZMailbox(userName);
/*      */     
/*  566 */     deleteMessages(mbox, "is:anywhere " + subjectSubstring);
/*      */     
/*      */ 
/*  569 */     deleteMessages(mbox, "in:trash " + subjectSubstring);
/*  570 */     deleteMessages(mbox, "in:junk " + subjectSubstring);
/*  571 */     deleteMessages(mbox, "in:sent " + subjectSubstring);
/*      */     
/*      */ 
/*  574 */     deleteMessages(mbox, "subject: " + subjectSubstring);
/*      */     
/*      */ 
/*  577 */     for (ZTag tag : mbox.getAllTags()) {
/*  578 */       if (tag.getName().contains(subjectSubstring)) {
/*  579 */         mbox.deleteTag(tag.getId());
/*      */       }
/*      */     }
/*      */     
/*      */ 
/*  584 */     for (ZFolder folder : mbox.getAllFolders()) {
/*  585 */       if (folder.getName().contains(subjectSubstring)) {
/*  586 */         mbox.deleteFolder(folder.getId());
/*      */       }
/*      */     }
/*      */     
/*      */ 
/*  591 */     for (ZContact contact : mbox.getAllContacts(null, ZMailbox.ContactSortBy.nameAsc, false, null)) {
/*  592 */       String fullName = (String)contact.getAttrs().get("fullName");
/*  593 */       if ((fullName != null) && (fullName.contains(subjectSubstring))) {
/*  594 */         mbox.deleteContact(contact.getId());
/*      */       }
/*      */     }
/*      */     
/*      */ 
/*  599 */     List<ZDataSource> dataSources = mbox.getAllDataSources();
/*  600 */     for (ZDataSource ds : dataSources) {
/*  601 */       if (ds.getName().contains(subjectSubstring)) {
/*  602 */         mbox.deleteDataSource(ds);
/*      */       }
/*      */     }
/*      */     
/*      */ 
/*  607 */     List<String> ids = search(mbox, subjectSubstring, "appointment");
/*  608 */     if (!ids.isEmpty()) {
/*  609 */       mbox.deleteItem(StringUtil.join(",", ids), null);
/*      */     }
/*      */     
/*      */ 
/*  613 */     ids = search(mbox, subjectSubstring, "document");
/*  614 */     if (!ids.isEmpty()) {
/*  615 */       mbox.deleteItem(StringUtil.join(",", ids), null);
/*      */     }
/*      */     
/*  618 */     ZMailbox adminMbox = getZMailboxAsAdmin(userName);
/*  619 */     adminMbox.emptyDumpster();
/*      */   }
/*      */   
/*      */   private static void deleteMessages(ZMailbox mbox, String query) throws ServiceException
/*      */   {
/*  624 */     ZSearchParams params = new ZSearchParams(query);
/*  625 */     params.setTypes("message");
/*  626 */     List<ZSearchHit> hits = mbox.search(params).getHits();
/*  627 */     if (hits.size() > 0) {
/*  628 */       List<String> ids = new ArrayList();
/*  629 */       for (ZSearchHit hit : hits) {
/*  630 */         ids.add(hit.getId());
/*      */       }
/*  632 */       mbox.deleteMessage(StringUtil.join(",", ids));
/*      */     }
/*      */   }
/*      */   
/*  636 */   private static boolean sIsCliInitialized = false;
/*      */   
/*      */ 
/*      */   public static void cliSetup()
/*      */     throws ServiceException
/*      */   {
/*  642 */     if (!sIsCliInitialized) {
/*  643 */       CliUtil.toolSetup();
/*  644 */       Provisioning.setInstance(newSoapProvisioning());
/*  645 */       SoapTransport.setDefaultUserAgent("Zimbra Unit Tests", BuildInfo.VERSION);
/*  646 */       sIsCliInitialized = true;
/*      */     }
/*      */   }
/*      */   
/*      */   public static SoapProvisioning newSoapProvisioning() throws ServiceException {
/*  651 */     SoapProvisioning sp = new SoapProvisioning();
/*  652 */     sp.soapSetURI("https://localhost:7071/service/admin/soap/");
/*  653 */     sp.soapZimbraAdminAuthenticate();
/*  654 */     return sp;
/*      */   }
/*      */   
/*      */   public static SoapProvisioning newDelegatedSoapProvisioning(String login, String password) throws ServiceException {
/*  658 */     SoapProvisioning sp = new SoapProvisioning();
/*  659 */     sp.soapSetURI("https://localhost:7071/service/admin/soap/");
/*  660 */     sp.soapAdminAuthenticate(login, password);
/*  661 */     return sp;
/*      */   }
/*      */   
/*      */   public static void runTest(Class<?> testClass) {
/*  665 */     JUnitCore junit = new JUnitCore();
/*  666 */     junit.addListener(new TestLogger());
/*  667 */     ZimbraLog.test.info("Starting unit test %s.", new Object[] { testClass.getName() });
/*  668 */     junit.run(new Class[] { testClass });
/*      */   }
/*      */   
/*      */   public static ZMailbox getZMailbox(String username)
/*      */     throws ServiceException
/*      */   {
/*  674 */     ZMailbox.Options options = new ZMailbox.Options();
/*  675 */     options.setAccount(getAddress(username));
/*  676 */     options.setAccountBy(Key.AccountBy.name);
/*  677 */     options.setPassword("test123");
/*  678 */     options.setUri(getSoapUrl());
/*  679 */     return ZMailbox.getMailbox(options);
/*      */   }
/*      */   
/*      */   public static ZMailbox getZMailboxAsAdmin(String username) throws ServiceException {
/*  683 */     ZAuthToken adminAuthToken = newSoapProvisioning().getAuthToken();
/*  684 */     ZMailbox.Options options = new ZMailbox.Options(adminAuthToken, getSoapUrl());
/*  685 */     options.setTargetAccount(getAddress(username));
/*  686 */     options.setTargetAccountBy(Key.AccountBy.name);
/*  687 */     return ZMailbox.getMailbox(options);
/*      */   }
/*      */   
/*      */ 
/*      */   public static Account createAccount(String username)
/*      */     throws ServiceException
/*      */   {
/*  694 */     return createAccount(username, null);
/*      */   }
/*      */   
/*      */ 
/*      */   public static Account createAccount(String username, Map<String, Object> attrs)
/*      */     throws ServiceException
/*      */   {
/*  701 */     Provisioning prov = Provisioning.getInstance();
/*  702 */     String address = getAddress(username);
/*  703 */     return prov.createAccount(address, "test123", attrs);
/*      */   }
/*      */   
/*      */ 
/*      */   public static DistributionList createDistributionList(String dlName)
/*      */     throws ServiceException
/*      */   {
/*  710 */     Provisioning prov = Provisioning.getInstance();
/*  711 */     String address = getAddress(dlName);
/*  712 */     Map<String, Object> attrs = new HashMap();
/*  713 */     return prov.createDistributionList(address, attrs);
/*      */   }
/*      */   
/*      */ 
/*      */   public static void deleteDistributionList(String listName)
/*      */     throws ServiceException
/*      */   {
/*  720 */     Provisioning prov = Provisioning.getInstance();
/*      */     
/*      */ 
/*      */ 
/*  724 */     if (!(prov instanceof SoapProvisioning)) {
/*  725 */       prov = newSoapProvisioning();
/*      */     }
/*  727 */     DistributionList dl = prov.get(Key.DistributionListBy.name, getAddress(listName));
/*  728 */     if (dl != null) {
/*  729 */       prov.deleteDistributionList(dl.getId());
/*      */     }
/*      */   }
/*      */   
/*      */ 
/*      */   public static void deleteAccount(String username)
/*      */     throws ServiceException
/*      */   {
/*  737 */     Provisioning prov = Provisioning.getInstance();
/*      */     
/*      */ 
/*      */ 
/*  741 */     if (!(prov instanceof SoapProvisioning)) {
/*  742 */       prov = newSoapProvisioning();
/*      */     }
/*  744 */     SoapProvisioning soapProv = (SoapProvisioning)prov;
/*  745 */     GetAccountRequest gaReq = new GetAccountRequest(AccountSelector.fromName(username), Boolean.valueOf(false), Lists.newArrayList(new String[] { "zimbraId" }));
/*      */     try
/*      */     {
/*  748 */       GetAccountResponse resp = (GetAccountResponse)soapProv.invokeJaxb(gaReq);
/*  749 */       if (resp != null) {
/*  750 */         String id = null;
/*  751 */         for (Attr attr : resp.getAccount().getAttrList()) {
/*  752 */           if ("zimbraId".equals(attr.getKey())) {
/*  753 */             id = attr.getValue();
/*  754 */             break;
/*      */           }
/*      */         }
/*  757 */         if (null == id) {
/*  758 */           ZimbraLog.test.error("GetAccountResponse for '%s' did not contain the zimbraId", new Object[] { username });
/*      */         }
/*  760 */         prov.deleteAccount(id);
/*      */       }
/*      */     } catch (SoapFaultException sfe) {
/*  763 */       if (!sfe.getMessage().contains("no such account")) {
/*  764 */         ZimbraLog.test.error("GetAccountResponse for '%s' hit unexpected problem", username, sfe);
/*      */       }
/*      */     }
/*      */   }
/*      */   
/*      */   public static String getServerAttr(String attrName) throws ServiceException {
/*  770 */     Provisioning prov = Provisioning.getInstance();
/*  771 */     Server server = prov.getLocalServer();
/*  772 */     return server.getAttr(attrName, null);
/*      */   }
/*      */   
/*      */   public static void setServerAttr(String attrName, String attrValue) throws ServiceException {
/*  776 */     Provisioning prov = Provisioning.getInstance();
/*  777 */     Server server = prov.getLocalServer();
/*  778 */     Map<String, Object> attrs = new HashMap();
/*  779 */     attrs.put(attrName, attrValue);
/*  780 */     prov.modifyAttrs(server, attrs);
/*      */   }
/*      */   
/*      */   public static String getAccountAttr(String userName, String attrName) throws ServiceException {
/*  784 */     String accountName = getAddress(userName);
/*  785 */     Account account = Provisioning.getInstance().getAccount(accountName);
/*  786 */     return account.getAttr(attrName);
/*      */   }
/*      */   
/*      */   public static String[] getAccountMultiAttr(String userName, String attrName) throws ServiceException {
/*  790 */     String accountName = getAddress(userName);
/*  791 */     Account account = Provisioning.getInstance().getAccount(accountName);
/*  792 */     return account.getMultiAttr(attrName);
/*      */   }
/*      */   
/*      */   public static void setAccountAttr(String userName, String attrName, String attrValue) throws ServiceException {
/*  796 */     Provisioning prov = Provisioning.getInstance();
/*  797 */     Account account = prov.get(Key.AccountBy.name, getAddress(userName));
/*  798 */     Map<String, Object> attrs = new HashMap();
/*  799 */     attrs.put(attrName, attrValue);
/*  800 */     prov.modifyAttrs(account, attrs);
/*      */   }
/*      */   
/*      */   public static void setAccountAttr(String userName, String attrName, String[] attrValues) throws ServiceException {
/*  804 */     Provisioning prov = Provisioning.getInstance();
/*  805 */     Account account = prov.get(Key.AccountBy.name, getAddress(userName));
/*  806 */     Map<String, Object> attrs = new HashMap();
/*  807 */     attrs.put(attrName, attrValues);
/*  808 */     prov.modifyAttrs(account, attrs);
/*      */   }
/*      */   
/*      */   public static String getConfigAttr(String attrName) throws ServiceException {
/*  812 */     return Provisioning.getInstance().getConfig().getAttr(attrName, "");
/*      */   }
/*      */   
/*      */   public static void setConfigAttr(String attrName, String attrValue) throws ServiceException {
/*  816 */     Provisioning prov = Provisioning.getInstance();
/*  817 */     Config config = prov.getConfig();
/*  818 */     Map<String, Object> attrs = new HashMap();
/*  819 */     attrs.put(attrName, attrValue);
/*  820 */     prov.modifyAttrs(config, attrs);
/*      */   }
/*      */   
/*      */   public static String getDomainAttr(String userName, String attrName) throws ServiceException {
/*  824 */     Account account = getAccount(userName);
/*  825 */     return Provisioning.getInstance().getDomain(account).getAttr(attrName);
/*      */   }
/*      */   
/*      */   public static void setDomainAttr(String userName, String attrName, Object attrValue) throws ServiceException {
/*  829 */     Account account = getAccount(userName);
/*  830 */     Domain domain = Provisioning.getInstance().getDomain(account);
/*  831 */     Map<String, Object> attrs = new HashMap();
/*  832 */     attrs.put(attrName, attrValue);
/*  833 */     Provisioning.getInstance().modifyAttrs(domain, attrs);
/*      */   }
/*      */   
/*      */   public static void setDataSourceAttr(String userName, String dataSourceName, String attrName, String attrValue) throws ServiceException
/*      */   {
/*  838 */     Provisioning prov = Provisioning.getInstance();
/*  839 */     Account account = getAccount(userName);
/*  840 */     DataSource ds = prov.get(account, Key.DataSourceBy.name, dataSourceName);
/*  841 */     Map<String, Object> attrs = new HashMap();
/*  842 */     attrs.put(attrName, attrValue);
/*  843 */     prov.modifyAttrs(ds, attrs);
/*      */   }
/*      */   
/*      */ 
/*      */   public static void verifyTag(ZMailbox mbox, ZMessage msg, String tagName)
/*      */     throws Exception
/*      */   {
/*  850 */     List<ZTag> tags = mbox.getTags(msg.getTagIds());
/*  851 */     for (ZTag tag : tags) {
/*  852 */       if (tag.getName().equals(tagName)) {
/*  853 */         return;
/*      */       }
/*      */     }
/*  856 */     Assert.fail("Message not tagged with " + tagName);
/*      */   }
/*      */   
/*      */   public static ZMessage getMessage(ZMailbox mbox, String query) throws Exception {
/*  860 */     List<ZMessage> results = search(mbox, query);
/*  861 */     String errorMsg = String.format("Unexpected number of messages returned by query '%s'", new Object[] { query });
/*  862 */     Assert.assertEquals(errorMsg, 1, results.size());
/*  863 */     return (ZMessage)results.get(0);
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public static void verifyFlag(ZMailbox mbox, ZMessage msg, ZItem.Flag flag)
/*      */   {
/*  870 */     String flags = msg.getFlags();
/*  871 */     String errorMsg = String.format("Flag %s not found in %s", new Object[] { Character.valueOf(flag.getFlagChar()), msg.getFlags() });
/*  872 */     Assert.assertTrue(errorMsg, flags.indexOf(flag.getFlagChar()) >= 0);
/*      */   }
/*      */   
/*      */   public static ZFolder createFolder(ZMailbox mbox, String path) throws ServiceException {
/*  876 */     return createFolder(mbox, path, ZFolder.View.message);
/*      */   }
/*      */   
/*      */   public static ZFolder createFolder(ZMailbox mbox, String path, ZFolder.View view) throws ServiceException {
/*  880 */     String parentId = Integer.toString(1);
/*  881 */     String name = null;
/*  882 */     int idxLastSlash = path.lastIndexOf('/');
/*      */     
/*  884 */     if (idxLastSlash < 0) {
/*  885 */       name = path;
/*  886 */     } else if (idxLastSlash == 0) {
/*  887 */       name = path.substring(1);
/*      */     } else {
/*  889 */       String parentPath = path.substring(0, idxLastSlash);
/*  890 */       name = path.substring(idxLastSlash + 1);
/*  891 */       ZFolder parent = mbox.getFolderByPath(parentPath);
/*  892 */       if (parent == null) {
/*  893 */         String msg = String.format("Creating folder %s: parent %s does not exist", new Object[] { name, parentPath });
/*  894 */         throw ServiceException.FAILURE(msg, null);
/*      */       }
/*  896 */       parentId = parent.getId();
/*      */     }
/*      */     
/*  899 */     return mbox.createFolder(parentId, name, view, null, null, null);
/*      */   }
/*      */   
/*      */   public static ZFolder createFolder(ZMailbox mbox, String parentId, String folderName) throws ServiceException {
/*  903 */     return mbox.createFolder(parentId, folderName, ZFolder.View.message, null, null, null);
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */ 
/*      */   public static ZMountpoint createMountpoint(ZMailbox remoteMbox, String remotePath, ZMailbox localMbox, String mountpointName)
/*      */     throws ServiceException
/*      */   {
/*  920 */     ZFolder remoteFolder = remoteMbox.getFolderByPath(remotePath);
/*  921 */     if (remoteFolder == null) {
/*  922 */       remoteFolder = createFolder(remoteMbox, remotePath);
/*      */     }
/*  924 */     ZGetInfoResult remoteInfo = remoteMbox.getAccountInfo(true);
/*  925 */     remoteMbox.modifyFolderGrant(remoteFolder.getId(), ZGrant.GranteeType.all, null, "rwidx", null);
/*  926 */     return localMbox.createMountpoint(Integer.toString(1), mountpointName, null, null, null, ZMailbox.OwnerBy.BY_ID, remoteInfo.getId(), ZMailbox.SharedItemBy.BY_ID, remoteFolder.getId(), false);
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public static ZDataSource getDataSource(ZMailbox mbox, String name)
/*      */     throws ServiceException
/*      */   {
/*  934 */     for (ZDataSource ds : mbox.getAllDataSources()) {
/*  935 */       if (ds.getName().equals(name)) {
/*  936 */         return ds;
/*      */       }
/*      */     }
/*  939 */     return null;
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public static void importDataSource(ZDataSource dataSource, ZMailbox localMbox, ZMailbox remoteMbox)
/*      */     throws Exception
/*      */   {
/*  947 */     importDataSource(dataSource, localMbox, remoteMbox, true);
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public static void importDataSource(ZDataSource dataSource, ZMailbox localMbox, ZMailbox remoteMbox, boolean expectedSuccess)
/*      */     throws Exception
/*      */   {
/*  955 */     List<ZDataSource> dataSources = new ArrayList();
/*  956 */     dataSources.add(dataSource);
/*  957 */     localMbox.importData(dataSources);
/*  958 */     String type = dataSource.getType().toString();
/*      */     
/*      */     ZMailbox.ZImportStatus status;
/*      */     for (;;)
/*      */     {
/*  963 */       Thread.sleep(500L);
/*      */       
/*  965 */       status = null;
/*  966 */       for (ZMailbox.ZImportStatus iter : localMbox.getImportStatus()) {
/*  967 */         if (iter.getId().equals(dataSource.getId())) {
/*  968 */           status = iter;
/*      */         }
/*      */       }
/*  971 */       assertNotNull("No import status returned for data source " + dataSource.getName(), status);
/*  972 */       assertEquals("Unexpected data source type", type, status.getType());
/*  973 */       if (!status.isRunning()) {
/*      */         break;
/*      */       }
/*      */     }
/*  977 */     assertEquals(expectedSuccess, status.getSuccess());
/*  978 */     if (!expectedSuccess) {
/*  979 */       assertNotNull(status.getError());
/*      */     }
/*      */     
/*      */ 
/*  983 */     localMbox.noOp();
/*  984 */     if (remoteMbox != null) {
/*  985 */       remoteMbox.noOp();
/*      */     }
/*      */   }
/*      */   
/*      */ 
/*      */   public static SoapTransport getAdminSoapTransport()
/*      */     throws SoapFaultException, IOException, ServiceException
/*      */   {
/*  993 */     SoapHttpTransport transport = new SoapHttpTransport(getAdminSoapUrl());
/*      */     
/*      */ 
/*  996 */     Element auth = new Element.XMLElement(AdminConstants.AUTH_REQUEST);
/*  997 */     auth.addElement("name").setText(LC.zimbra_ldap_user.value());
/*  998 */     auth.addElement("password").setText(LC.zimbra_ldap_password.value());
/*      */     
/*      */ 
/* 1001 */     Element response = transport.invoke(auth);
/* 1002 */     String authToken = response.getElement("authToken").getText();
/* 1003 */     transport.setAuthToken(authToken);
/* 1004 */     transport.setAdmin(true);
/* 1005 */     return transport;
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public static SoapTransport getAdminSoapTransport(String adminName, String adminPassword)
/*      */     throws SoapFaultException, IOException, ServiceException
/*      */   {
/* 1013 */     SoapHttpTransport transport = new SoapHttpTransport(getAdminSoapUrl());
/*      */     
/*      */ 
/* 1016 */     Element auth = new Element.XMLElement(AdminConstants.AUTH_REQUEST);
/* 1017 */     auth.addElement("name").setText(adminName);
/* 1018 */     auth.addElement("password").setText(adminPassword);
/*      */     
/*      */ 
/* 1021 */     Element response = transport.invoke(auth);
/* 1022 */     String authToken = response.getElement("authToken").getText();
/* 1023 */     transport.setAuthToken(authToken);
/* 1024 */     return transport;
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public static void assertMessageContains(String message, String subMessage)
/*      */     throws IOException
/*      */   {
/* 1032 */     BufferedReader msgReader = new BufferedReader(new StringReader(message));
/* 1033 */     BufferedReader subReader = new BufferedReader(new StringReader(subMessage));
/* 1034 */     String firstLine = subReader.readLine();
/*      */     
/* 1036 */     boolean foundFirstLine = false;
/*      */     String line;
/* 1038 */     while ((line = msgReader.readLine()) != null) {
/* 1039 */       if (line.equals(firstLine)) {
/* 1040 */         foundFirstLine = true;
/*      */       }
/*      */     }
/*      */     
/*      */ 
/* 1045 */     String context = String.format("Could not find '%s' in message:\n%s", new Object[] { firstLine, message });
/* 1046 */     assertTrue(context, foundFirstLine);
/*      */     for (;;)
/*      */     {
/* 1049 */       line = msgReader.readLine();
/* 1050 */       String subLine = subReader.readLine();
/* 1051 */       if ((line == null) || (subLine == null)) {
/*      */         break;
/*      */       }
/* 1054 */       assertEquals(subLine, line);
/*      */     }
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */ 
/*      */   public static void assertEquals(Element expected, Element actual)
/*      */   {
/* 1063 */     assertEquals(expected, actual, expected.prettyPrint(), actual.prettyPrint());
/*      */   }
/*      */   
/*      */   private static void assertEquals(Element expected, Element actual, String expectedDump, String actualDump) {
/* 1067 */     assertEquals(expected.getName(), actual.getName());
/* 1068 */     List<Element> expectedChildren = expected.listElements();
/* 1069 */     List<Element> actualChildren = actual.listElements();
/* 1070 */     String context = String.format("Element %s, expected:\n%s\nactual:\n%s", new Object[] { expected.getName(), expectedDump, actualDump });
/*      */     
/* 1072 */     assertEquals(context + " children", getElementNames(expectedChildren), getElementNames(actualChildren));
/*      */     
/*      */ 
/* 1075 */     for (int i = 0; i < expectedChildren.size(); i++) {
/* 1076 */       assertEquals((Element)expectedChildren.get(i), (Element)actualChildren.get(i), expectedDump, actualDump);
/*      */     }
/*      */     
/*      */ 
/* 1080 */     assertEquals(expected.getTextTrim(), actual.getTextTrim());
/*      */     
/*      */ 
/* 1083 */     Set<Element.Attribute> expectedAttrs = expected.listAttributes();
/* 1084 */     Set<Element.Attribute> actualAttrs = actual.listAttributes();
/* 1085 */     assertEquals(context + " attributes", getAttributesAsString(expectedAttrs), getAttributesAsString(actualAttrs));
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public static void assertEquals(byte[] expected, byte[] actual)
/*      */   {
/* 1092 */     if ((expected == null) && (actual == null)) {
/* 1093 */       return;
/*      */     }
/* 1095 */     if (expected == null) {
/* 1096 */       Assert.fail("expected was null but actual was not.");
/*      */     }
/* 1098 */     if (actual == null) {
/* 1099 */       Assert.fail("expected was not null but actual was.");
/*      */     }
/* 1101 */     assertEquals("Arrays have different length.", expected.length, actual.length);
/* 1102 */     for (int i = 0; i < expected.length; i++) {
/* 1103 */       assertEquals("Data mismatch at byte " + i, expected[i], actual[i]);
/*      */     }
/*      */   }
/*      */   
/*      */   private static String getElementNames(List<Element> elements) {
/* 1108 */     StringBuilder buf = new StringBuilder();
/* 1109 */     for (Element e : elements) {
/* 1110 */       if (buf.length() > 0) {
/* 1111 */         buf.append(",");
/*      */       }
/* 1113 */       buf.append(e.getName());
/*      */     }
/* 1115 */     return buf.toString();
/*      */   }
/*      */   
/*      */   private static String getAttributesAsString(Set<Element.Attribute> attrs) {
/* 1119 */     Set<String> attrStrings = new TreeSet();
/* 1120 */     for (Element.Attribute attr : attrs) {
/* 1121 */       attrStrings.add(String.format("%s=%s", new Object[] { attr.getKey(), attr.getValue() }));
/*      */     }
/* 1123 */     return StringUtil.join(",", attrStrings);
/*      */   }
/*      */   
/*      */   public static String getHeaderValue(ZMailbox mbox, ZMessage msg, String headerName) throws Exception {
/* 1127 */     String content = msg.getContent();
/* 1128 */     if (content == null) {
/* 1129 */       content = getContent(mbox, msg.getId());
/*      */     }
/* 1131 */     assertNotNull("Content was not fetched from the server", content);
/* 1132 */     MimeMessage mimeMsg = new ZMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(content.getBytes()));
/*      */     
/* 1134 */     return mimeMsg.getHeader(headerName, null);
/*      */   }
/*      */   
/*      */   public static ZMailbox.ZAppointmentResult createAppointment(ZMailbox mailbox, String subject, String attendee, Date startDate, Date endDate) throws ServiceException
/*      */   {
/* 1139 */     ZInvite invite = new ZInvite();
/* 1140 */     ZInvite.ZComponent comp = new ZInvite.ZComponent();
/*      */     
/* 1142 */     comp.setStatus(ZInvite.ZStatus.CONF);
/* 1143 */     comp.setClassProp(ZInvite.ZClass.PUB);
/* 1144 */     comp.setTransparency(ZInvite.ZTransparency.O);
/*      */     
/* 1146 */     comp.setStart(new ZDateTime(startDate.getTime(), false, mailbox.getPrefs().getTimeZone()));
/* 1147 */     comp.setEnd(new ZDateTime(endDate.getTime(), false, mailbox.getPrefs().getTimeZone()));
/* 1148 */     comp.setName(subject);
/* 1149 */     comp.setOrganizer(new ZInvite.ZOrganizer(mailbox.getName()));
/*      */     
/* 1151 */     if (attendee != null) {
/* 1152 */       attendee = addDomainIfNecessary(attendee);
/* 1153 */       ZInvite.ZAttendee zattendee = new ZInvite.ZAttendee();
/* 1154 */       zattendee.setAddress(attendee);
/* 1155 */       zattendee.setRole(ZInvite.ZRole.REQ);
/* 1156 */       zattendee.setParticipantStatus(ZInvite.ZParticipantStatus.NE);
/* 1157 */       zattendee.setRSVP(true);
/* 1158 */       comp.getAttendees().add(zattendee);
/*      */     }
/*      */     
/* 1161 */     invite.getComponents().add(comp);
/*      */     
/* 1163 */     ZMailbox.ZOutgoingMessage m = null;
/* 1164 */     if (attendee != null) {
/* 1165 */       m = getOutgoingMessage(attendee, subject, "Test appointment", null);
/*      */     }
/*      */     
/* 1168 */     return mailbox.createAppointment("10", null, m, invite, null);
/*      */   }
/*      */   
/*      */   public static void sendInviteReply(ZMailbox mbox, String inviteId, String organizer, String subject, ZMailbox.ReplyVerb replyVerb) throws ServiceException
/*      */   {
/* 1173 */     organizer = addDomainIfNecessary(organizer);
/* 1174 */     ZMailbox.ZOutgoingMessage msg = getOutgoingMessage(organizer, subject, "Reply to appointment " + inviteId, null);
/* 1175 */     mbox.sendInviteReply(inviteId, "0", replyVerb, true, null, null, msg);
/*      */   }
/*      */   
/*      */   public static ZFilterRule getFilterRule(ZMailbox mbox, String ruleName) throws ServiceException {
/* 1179 */     for (ZFilterRule rule : mbox.getIncomingFilterRules(true).getRules()) {
/* 1180 */       if (rule.getName().equals(ruleName)) {
/* 1181 */         return rule;
/*      */       }
/*      */     }
/* 1184 */     return null;
/*      */   }
/*      */   
/*      */   public static ZDocument createDocument(ZMailbox mbox, String folderId, String name, String contentType, byte[] content) throws ServiceException
/*      */   {
/* 1189 */     return createDocument(mbox, folderId, name, contentType, content, false);
/*      */   }
/*      */   
/*      */   public static ZDocument createDocument(ZMailbox mbox, String folderId, String name, String contentType, byte[] content, boolean isNote) throws ServiceException
/*      */   {
/* 1194 */     String attachId = mbox.uploadAttachment(name, content, contentType, 0);
/* 1195 */     String docId = mbox.createDocument(folderId, name, attachId, isNote);
/* 1196 */     return mbox.getDocument(docId);
/*      */   }
/*      */   
/*      */   public static ZIdentity getDefaultIdentity(ZMailbox mbox) throws ServiceException {
/* 1200 */     for (ZIdentity ident : mbox.getIdentities()) {
/* 1201 */       if (ident.getName().equalsIgnoreCase("DEFAULT")) {
/* 1202 */         return ident;
/*      */       }
/*      */     }
/* 1205 */     Assert.fail("Could not find default identity for " + mbox.getName());
/* 1206 */     return null;
/*      */   }
/*      */   
/*      */   public static boolean checkLocalBlobs()
/*      */   {
/* 1211 */     return StoreManager.getInstance() instanceof FileBlobStore;
/*      */   }
/*      */   
/*      */   public static byte[] readInputStream(InputStream is) throws IOException {
/* 1215 */     ByteArrayOutputStream baos = new ByteArrayOutputStream();
/* 1216 */     int i = -1;
/* 1217 */     while ((i = is.read()) >= 0) {
/* 1218 */       baos.write(i);
/*      */     }
/* 1220 */     return baos.toByteArray();
/*      */   }
/*      */   
/*      */   public static boolean bytesEqual(byte[] b1, InputStream is) throws IOException {
/* 1224 */     return bytesEqual(b1, readInputStream(is));
/*      */   }
/*      */   
/*      */   public static boolean bytesEqual(byte[] b1, byte[] b2) {
/* 1228 */     if (b1.length != b2.length) {
/* 1229 */       return false;
/*      */     }
/* 1231 */     for (int i = 0; i < b1.length; i++) {
/* 1232 */       if (b1[i] != b2[i]) {
/* 1233 */         return false;
/*      */       }
/*      */     }
/* 1236 */     return true;
/*      */   }
/*      */   
/*      */ 
/*      */ 
/*      */   public static void updateMailItemChangeDateAndFlag(Mailbox mbox, int itemId, long changeDate, int flagValue)
/*      */     throws ServiceException
/*      */   {
/* 1244 */     DbPool.DbConnection conn = DbPool.getConnection(mbox);
/*      */     try
/*      */     {
/* 1247 */       StringBuilder sql = new StringBuilder();
/* 1248 */       sql.append("UPDATE ").append(DbMailItem.getMailItemTableName(mbox)).append(" SET change_date = ").append(changeDate);
/*      */       
/* 1250 */       if (flagValue > 0) {
/* 1251 */         sql.append(", flags = ").append(flagValue);
/*      */       }
/* 1253 */       sql.append(" WHERE id = ").append(itemId);
/* 1254 */       DbUtil.executeUpdate(conn, sql.toString());
/*      */     } finally {
/* 1256 */       conn.commit();
/* 1257 */       conn.closeQuietly();
/*      */     }
/*      */   }
/*      */   
/*      */   protected static void setLCValue(KnownKey key, String newValue) throws DocumentException, ConfigException, IOException, ServiceException
/*      */   {
/* 1263 */     LocalConfig lc = new LocalConfig(null);
/* 1264 */     if (newValue == null) {
/* 1265 */       lc.remove(key.key());
/*      */     } else {
/* 1267 */       lc.set(key.key(), newValue);
/*      */     }
/* 1269 */     lc.save();
/* 1270 */     SoapProvisioning prov = newSoapProvisioning();
/* 1271 */     ReloadLocalConfigRequest req = new ReloadLocalConfigRequest();
/* 1272 */     ReloadLocalConfigResponse resp = (ReloadLocalConfigResponse)prov.invokeJaxb(req);
/* 1273 */     assertNotNull("ReloadLocalConfigResponse", resp);
/*      */   }
/*      */   
/*      */   public static SoapTransport authUser(String acctName, String password) throws Exception {
/* 1277 */     AccountSelector acct = new AccountSelector(AccountBy.name, acctName);
/*      */     
/* 1279 */     SoapHttpTransport transport = new SoapHttpTransport(getSoapUrl());
/* 1280 */     AuthRequest req = new AuthRequest(acct, password);
/* 1281 */     AuthResponse resp = (AuthResponse)SoapTest.invokeJaxb(transport, req);
/* 1282 */     transport.setAuthToken(resp.getAuthToken());
/* 1283 */     return transport;
/*      */   }
/*      */   
/*      */   public static void grantRightToAdmin(SoapProvisioning adminSoapProv, TargetType targetType, String targetName, String granteeName, String rightName) throws ServiceException
/*      */   {
/* 1288 */     GranteeSelector grantee = new GranteeSelector(GranteeType.usr, GranteeSelector.GranteeBy.name, granteeName);
/* 1289 */     EffectiveRightsTargetSelector target = null;
/* 1290 */     if (targetName == null) {
/* 1291 */       target = new EffectiveRightsTargetSelector(targetType, null, null);
/*      */     } else {
/* 1293 */       target = new EffectiveRightsTargetSelector(targetType, TargetBy.name, targetName);
/*      */     }
/*      */     
/* 1296 */     RightModifierInfo right = new RightModifierInfo(rightName);
/* 1297 */     GrantRightResponse grResp = (GrantRightResponse)adminSoapProv.invokeJaxb(new GrantRightRequest(target, grantee, right));
/* 1298 */     assertNotNull("GrantRightResponse for " + right.getValue(), grResp);
/*      */   }
/*      */ }


/* Location:              /home/mint/zimbrastore.jar!/com/zimbra/qa/unittest/TestUtil.class
 * Java compiler version: 7 (51.0)
 * JD-Core Version:       0.7.1
 */